var express = require('express');
var router = express.Router();
var sql = require('./../sql');
var Pro = require('./../sql/col/products');

/* GET users listing. */
/**
 * @api {get} api/search 获取搜索的产品数据
 * @apiDescription 获取搜索的产品数据
 * @apiGroup 搜索接口
 * @apiParam { string } keyword 关键字
 * @apiParam { number } limit 每页显示个数（默认值10）
 * @apiParam { number } count 页码（默认值0
 * @apiSuccessExample { json } Success-Response:
 * res.send({
      code: '200',
      message: '获取搜索的产品数据',
      data
    });
 * @apiSampleRequest /api/search
 * @apiVersion 1.0.0
 */
router.get('/', function(req, res, next) {
  // 1.接收分类的数据，依据分类查询数据，确定显示的字段
  let limit = req.query.limit * 1 || 10
  let count = req.query.count * 1 || 0
  const { keyword } = req.query
  var reg = new RegExp(keyword, 'i');
  // $regex用来设置匹配字符串的正则表达式
  var searchObj = [ 
    { name: { $regex: reg} },
    { desc: { $regex: reg} },
    { keyword: { $regex: reg} }
  ]
   // 或查询
  sql.paging(Pro, { $or: searchObj }, { _id: 0 }, limit, count).then(data => {
    res.send({
      code: '200',
      message: '搜索列表',
      len: data.length, // 告诉用户请求了多少条数据,
      data
    });
  })
});

module.exports = router;
